<?php
require_once APPLICATION_PATH . '/models/Events.php';

class IndexController  extends Zend_Controller_Action {

    public function init() {
        $this->matchtemplate = "<div id='%aid%' class='match'><p>%sport%: %competition%</p><a href='/event//%id%'>%participants%</a>%actions%</div>";
        $this->actiontemplate = "<p>%part%ª parte - %min%': %action% de %participant%</p>";
    }

    public function indexAction()
    {
        $this->showHome();
    }

    private function showHome()
    {
        $this->sports = Zend_Registry::get('sports');
        $this->emodel = new Model_Events();
        $this->view->events = array();

        $request = $this->getRequest();

        $this->auth = Zend_Auth::getInstance ();
        if ($this->auth->hasIdentity()) {
            $this->view->isAuth = true;
            $users = array($this->auth->getIdentity()->_id);
            $events = $this->emodel->find(array("u"=>array("\$in"=>$users)), array("lu"=>-1), 10);
        } else {
            require_once APPLICATION_PATH . '/forms/Join.php';
            $this->view->isAuth = false;
            $this->view->joinform = new Form_Join( );
            $events = $this->emodel->find(array(), array("lu"=>-1), 5);
        }

        foreach ($events as $e) {
            $event = new stdClass();
            $event->id = $e['_id']->__toString();
            $event->participants = $e['ps'];
            $event->competition = $e["c"];
            $event->sport = $this->sports[$e["s"]];

            if (isset($e['as'])) {
                $event->lastindex = count($e['as'])-1;
                $event->last = $e['as'][$event->lastindex];
                $event->part = isset($e['tm'])?count($e['tm']):1;
                $event->time = ((int)($event->last["t"]/60));
            } else {
                $event->lastindex = -1;
            }
            $this->view->events []= $event;
        }

        $this->view->matchtemplate = $this->matchtemplate;
        $this->view->actiontemplate = $this->actiontemplate;
        
        $jquery = $this->view->jQuery();
        $onload = " var sports = ".json_encode($this->sports).";\n".
                  " function refresh() {".
                        "$.ajax('/api?method=recentEvents', {type:'json', ".
                            "success:function(data){".
                                "app = '';".
                                "for (i in data) { event = data[i];".
                                    "var actions='', last = -1; if ('as' in event) { part = event.tm.length; last = event.as.length-1; actions = \"$this->actiontemplate\".replace('%part%', part)".
                                    ".replace('%min%', Math.round(event.as[last].t/60)).replace('%action%', sports[event.s].actions['action_'+event.as[last].a].name)".
                                    ".replace('%participant%', event.ps[event.as[last].p].n); } ".
                                    "var aid = event._id+last; if ($('#'+aid).length>0) continue; ".
                                    "app += \"$this->matchtemplate\".replace('%aid%', aid)".
                                    ".replace('%sport%', event.s).replace('%competition%', event.c)".
                                    ".replace('%id%', event._id)".
                                    ".replace('%participants%',event.ps[0].s+' - '+event.ps[0].n+' vs. '+event.ps[1].n+' - '+event.ps[1].s)".
                                    ".replace('%actions%', actions);".
                                "}".
                                "app = $(app); app.hide();".
                                "$('#recent-actions').prepend(app); app.slideDown(); $('#recent-actions .match:last').each(function(index){if ($(this).position().top>$('#recent').height()) { $(this).remove()}});".
                        "}});".
                    "}; ".
                    "setInterval(refresh,5000);";
        $jquery->addOnload($onload);
    }

}
